query-wrapper<template>
  <div class="app-container">
    <el-form :model="queryParams">
      <el-row class="query-wrapper">
        <el-select v-model="queryParams.vesselName" filterable clearable  allow-create placeholder="Vessel" 
          @change="selectVessel(queryParams)" style="width:180px">
          <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
          </el-option>
        </el-select>
        &nbsp;&nbsp;
        <el-select v-model="queryParams.voyageNo" filterable clearable allow-create placeholder="Voyage"  style="width:100px"
          @change="selectVoyage">
          <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages">
          </el-option>
        </el-select>
        &nbsp;&nbsp;
        <el-select v-model="queryParams.pol" filterable clearable allow-create placeholder="PORT OF LOADING">
          <el-option :key="item.portName" :label="item.portName" :value="item.portName" v-for="item in pols">
          </el-option>
        </el-select>
        &nbsp;&nbsp;
        <el-select v-model="queryParams.pod" filterable clearable allow-create placeholder="PORT OF DISCHARGE">
          <el-option :key="item.portName" :label="item.portName" :value="item.portName" v-for="item in pods">
          </el-option>
        </el-select>
        &nbsp;&nbsp;
        <el-input v-model="queryParams.blNo" placeholder="B/L No" style="width:170px" clearable/>
        &nbsp;&nbsp;
        <el-button type="primary" icon="search" @click="search">Search</el-button> 
        <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
      </el-row>
      <el-row class="query-wrapper" style="margin-top: 20px;">
        <el-button type="success" plain icon="upload" @click="uploadFileForm" v-hasPermi="['exportForAgent:import']">Import</el-button>
        <el-button type="primary" plain icon="plus" @click="addClickEvent" v-hasPermi="['exportForAgent:add']">Create New</el-button> 
        <!-- <el-button type="primary" @click="handleExport"  v-hasPermi="['exportForAgent:print']">Export</el-button> -->
      </el-row>
    </el-form>
    <!-- </div> -->
    <el-empty v-if="listData == null || listData.length === 0" description="No Data" />
    <h3 style="text-align: center" v-if="listData!=null && listData.length > 0"><strong>CARGO MANIFEST</strong></h3>
	
    <div v-for="(item, index) in listData" :key="index" class="item-box">
      <el-row class="manifest-tip-item__wrapper">
        <el-col :span="6" class="manifest-tip-item">
          <span class="title">{{ item.agencyEn }} </span>
        </el-col>
        <el-col :span="6" class="manifest-tip-item">
          <span class="title">{{ item.agencyCn }}</span>
        </el-col>
         <el-col :offset="6" :span="6" class="manifest-tip-item">
        <el-button type="primary" @click="handleCloseAll">Close</el-button>
        <el-button type="warning"   @click="handleExport(item)" v-hasPermi="['exportForAgent:export']">Export</el-button>
        <el-button type="danger" :disabled="!singles[index]"  @click="removeClickEvent" >Delete</el-button>

         <!-- <span class="btn-primary"  v-if=" scope.row.id != null && scope.row.status != 1" @click="removeClickEvent(scope.row.id)"> Delete</span>&nbsp;&nbsp; -->
        </el-col>
      </el-row>
      <el-row class="manifest-tip-item__wrapper">
        <el-col :span="6" class="manifest-tip-item">
          <span class="title1"><strong>VESSEL NAME</strong></span>{{ item.vesselName }}
        </el-col> 
        <el-col :span="7" class="manifest-tip-item"> 
          <span class="title"><strong>VOYAGE</strong></span>{{ item.voyageNo }}
        </el-col>
        <el-col :span="7" class="manifest-tip-item">
          <span class="title"><strong>FLAG</strong></span>{{ item.flagState }}
        </el-col>
        <el-col :span="3" class="manifest-tip-item">
          <span class="title2"><strong>IMO No.</strong></span>{{ item.imoNumber }}
        </el-col>
      </el-row>
      <el-row class="manifest-tip-item__wrapper">
        <el-col :span="6" class="manifest-tip-item">
          <span class="title1"><strong>PORT OF LOADING</strong></span>{{ item.pol }} 
        </el-col>  
        <el-col :span="7" class="manifest-tip-item"> 
          <span class="title"><strong>PORT OF DISCHARGING</strong></span>
          <!-- <el-input   v-if="isEdit&&editIndex === index" style="width: 30%;" v-model="item.pod"></el-input> -->
          <el-select  v-if="isEdit&&editIndex === index" v-model="item.pod" filterable clearable style="width: 30%">
            <el-option v-for="val in pods" :key="val.fullPortName" :label="val.fullPortName" :value="val.fullPortName"/>
          </el-select>
          <span v-else  >{{item.pod}}</span>
        <span style="margin-left: 10px;">
          <el-icon>
            <Finished v-if="isEdit&&editIndex === index"  @click="editPrentPod(false,index,item)" /> 
            <Edit v-else @click="editPrentPod(true,index)" />
          </el-icon>
        </span>
        </el-col>
        <el-col :span="7" class="manifest-tip-item">
          <span class="title"><strong>DATE OF DEPARTURE</strong></span>{{ item.atd }}
        </el-col>
        <el-col :span="3" class="manifest-tip-item">
          <span class="title2"><strong>N.R.T.</strong></span>{{ item.nrt }}
        </el-col>
      </el-row>
      <!-- <el-row class="manifest-tip-item__wrapper">
        <el-col :span="8" class="manifest-tip-item" style="padding-top: 0;">
          <el-button type="primary" @click="onMerge({ item, index })">Combine</el-button>
        </el-col>
      </el-row> -->

      <el-table :ref="el => (tableRefs[index] = el)" stripe :data="item.details" row-key="id" style="width: 100%"  :border="true" 
		  @sort-change="handleSortChange"  
		  @selection-change="(selection) => handleSelectionChange(selection,item, index) "   
		  @row-dblclick="editClickEvent" 
		  show-overflow-tooltip :cell-style="{textAlign:'center'}">
        <el-table-column type="selection"  :selectable="(row) => (row.id && row.status !=1)"  width="55" />
        <el-table-column prop="blNo" label="B/L NO." width="160" />
        <el-table-column prop="marks" label="MARKS & NOS." width="120"  />
        <el-table-column prop="goodsDesc" label="DESCRIPTION OF GOODS" width="200"/>
        <el-table-column  label="NO.& KIND OF PKGS" width="180">
          <template #header>
              NO.& KIND OF PKGS
          </template>
          <template #default="scope">
              <table width="100%"><tbody><tr><td style="width:50%">{{ scope.row.totalUnits }}</td><td style="width:50%">{{ scope.row.unit }}</td></tr></tbody></table>
          </template>
        </el-table-column>
        <el-table-column prop="totalWeight" label="G/W(KGS)" width="160" header-align="center">
        </el-table-column>
        <el-table-column prop="totalVolume" label="MEASUREMENT(M³)" width="160"   />
        <el-table-column prop="shipper" label="SHIPPER" width="200"   />
        <el-table-column prop="consignee" label="CONSIGNEE" width="200"   />
        <el-table-column prop="notifyParty" label="NOTIFY PARTY" width="300"  />
        <!-- <el-table-column prop="masterReceipt" label="M.R" min-width="150"> 
          <template #default="scope" > 
            <PreViewImageUpload  v-if="scope.row.id != null" :record="scope.row" :isTable="false" :isShowDel="false"  :photos="scope.row.masterReceipt?[scope.row.masterReceipt]:[]" :url="uploadUrl" :id="scope.row.id" :limit="1" @onSuccess="submitUploadForm" />
          </template>
        </el-table-column>    -->
        <el-table-column prop="remark" label="REMARKS" width="120"  />
        <el-table-column prop="createBy" label="Created By" width="120"  />
        <el-table-column prop="createTime" label="Time Created" width="140"  />
        <el-table-column prop="updateBy" label="Update By" width="120"  />
        <el-table-column prop="status" label="Status" width="80" fixed="right">
          <template #default="scope" > 
            {{ statuss[scope.row.status] }}
            </template>
         </el-table-column> 
        <el-table-column label="Operation" width="150" fixed="right" v-if="false">
          <template #default="scope">
            <span class="btn-primary"  v-if="scope.row.id != null" @click="editClickEvent(scope.row,item)">{{
              $t("ship.button.edit") }}</span>&nbsp;&nbsp; 
              <span class="btn-primary"  v-if="scope.row.id != null && scope.row.status == 0" @click="handleClose(scope.row)">Close</span>&nbsp;&nbsp;
              <span class="btn-primary"  v-if=" scope.row.id != null && scope.row.status != 1" @click="removeClickEvent(scope.row.id)"> Delete</span>&nbsp;&nbsp;
          </template>
        </el-table-column>
      </el-table> 
    </div> 
        <pagination
        v-show="total > 0"
        :total="total"
        :page="queryParams.pageNum"
        :limit="queryParams.pageSize"
        @pagination="pageQuery"
        style="float: right"
      />


    <el-dialog  destroy-on-close draggable :title="dialogTitle" v-model="dialogFormVisible" style="width:1000px">
      <el-form :model="formParam" :rules="rules" ref="custForm" class="addupdate-ruleForm">
    <!-- 第一行: 3 列 -->
    <el-row v-if="isAdd">
      <el-col :span="9">
        <el-form-item label="B/L No." label-width="170px" prop="blNo" required>
          <el-input v-model="formParam.blNo"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="7">
        <el-form-item label="Agent For English" label-width="120px" prop="agencyEn" required>
          <el-input v-model="formParam.agencyEn"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="Agent For Chinese" label-width="120px" prop="agencyCn">
          <el-input v-model="formParam.agencyCn"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 后续行: 2 列 -->
    <el-row v-if="isAdd">
      <el-col :span="12">
        <el-form-item label="Vessel Name" label-width="170px" prop="vesselName" required>
          <el-select v-model="formParam.vesselName" filterable clearable placeholder="choose vessel" style="width: 70%" @change="selectVessel(formParam)">
            <el-option v-for="item in vessels" :key="item.vesselName" :label="item.vesselName" :value="item.vesselName"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="Voyage" label-width="170px" prop="voyageNo" required>
          <el-select v-model="formParam.voyageNo" style="width: 70%" filterable clearable placeholder="Voyage" @change="selectVoyage">
            <el-option v-for="item in voyages" :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo"/>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row v-if="isAdd">
      <el-col :span="12">
        <el-form-item label="POL" label-width="170px" prop="pol" required>
          <el-select v-model="formParam.pol" filterable clearable placeholder="PORT OF LOADING" style="width: 70%">
            <el-option v-for="item in pols" :key="item.fullPortName" :label="item.fullPortName" :value="item.fullPortName"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="POD" label-width="170px" prop="pod" required>
          <el-select v-model="formParam.pod" filterable clearable placeholder="PORT OF DISCHARGING" style="width: 70%">
            <el-option v-for="item in pods" :key="item.fullPortName" :label="item.fullPortName" :value="item.fullPortName"/>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
  <el-row v-if="!isAdd">
    <el-col :span="12">
      <el-form-item label="PORT OF DISCHARGE" label-width="170px">
        <el-select v-model="formParam.pod" filterable clearable placeholder="PORT OF DISCHARGE" style="width: 70%">
          <el-option v-for="item in pods" :key="item.fullPortName" :label="item.fullPortName" :value="item.fullPortName"/>
        </el-select>
      </el-form-item>
    </el-col>
  </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="MARKS & NOS." label-width="170px" prop="marks" required>
          <el-input type="textarea" v-model="formParam.marks"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="DESCRIPTION OF GOODS" label-width="220px" prop="goodsDesc" required>
          <el-input type="textarea" v-model="formParam.goodsDesc"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="12">
        <el-form-item label="NO.& KIND OF PKGS" label-width="170px" prop="totalUnits" required>
          <el-input-number v-model="formParam.totalUnits" style="width: 70%"/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="Unit" label-width="170px" prop="unit" required>
          <el-select v-model="formParam.unit" style="width: 70%">
            <el-option v-for="item in units" :key="item" :value="item"/>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="12">
        <el-form-item label="G/W(KGS)" label-width="170px" prop="totalWeight" required>
          <el-input-number v-model="formParam.totalWeight" style="width: 70%"/>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="MEASUREMENT(M³)" label-width="170px" prop="totalVolume" required>
          <el-input-number v-model="formParam.totalVolume" style="width: 70%"/>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="12">
        <el-form-item label="SHIPPER" label-width="170px" prop="shipper" required>
          <el-input type="textarea" v-model="formParam.shipper"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="CONSIGNEE" label-width="170px" prop="consignee" required>
          <el-input type="textarea" v-model="formParam.consignee"></el-input>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="12">
        <el-form-item label="NOTIFY PARTY" label-width="170px" prop="notifyParty">
          <el-input type="textarea" v-model="formParam.notifyParty"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="REMARKS" label-width="170px" prop="remark">
          <el-input type="textarea" v-model="formParam.remark"></el-input>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">{{ $t("ship.button.cancel") }}</el-button> 
            <el-button type="primary" @click="submitForm">{{ $t("ship.button.submit") }}</el-button>
          </span>
        </template>
    </el-dialog>
    <!-- <FileUpload ref="fileUploadRef" :url="downTemplateUrl" :isAlink="false" :queryParams="queryParams" :templateFile=templateFile
      :uploadFileUrl="uploadFileUrl" :fileType="fileType" @update:modelValue="updateFileUpload" /> -->
    <FileUploadStep ref="fileUploadRef" :templateFile="templateFile" :url="downTemplateUrl" :isAlink="false" 
      :queryParams="queryParams" :uploadFileUrl="uploadFileUrl" :fileType="fileType" @update:modelValue="updateFileUpload"  />
  </div>
</template>
<script lang="ts" setup name="fromPolAgency">
import { ref, onMounted, reactive } from "vue";
import { ElNotification, ElMessageBox, ElMessage } from "element-plus";
import { downloadFile } from "@/utils/downloadFile";
import service from "@/utils/request"; 
import { useTablesDrag } from '@/hooks/useHooks';  
const { proxy, tableRefs, initTableDrag } = useTablesDrag() 

let vessels = ref([] as any);
const total = ref(0);
const isLoading = ref(false);
const statuss = ["draft","close"]
let voyages = ref([] as any);
let pols = ref([] as any);
let pods = ref([] as any);
const isEdit = ref(false) // 是否编辑
const editIndex = ref(null) // 编辑的索引

const multiples = ref({})
const singles = ref({})

onMounted(async () => { 
  let result = await service.get("/shipping/schedule/getAllSchedule");
  if (result) {
    vessels.value = result.data;
  }
});

const rules = ref({
  agencyEn: [{ required: true, message: "Agent is required" }],
  unit: [{ required: true, message: "Unit is required" }],
  vesselName: [{ required: true, message: "Vessel Name is required" }],
  voyageNo: [{ required: true, message: "Voyage is required" }],
  totalUnits:[{required: true, message: "NO.& KIND OF PKGS is required"}],
  totalWeight:[{required: true, message: "G/W(KGS) is required"}],
  totalVolume :[{required: true, message: "MEASUREMENT(M³) is required"}]
});
const uploadFileUrl = "/shipping/cargoManifest/uploadFile"
const templateFile = "exportForAgent.xlsx"
const handleExport = (item) => {
  downloadFile("/shipping/cargoManifest/export/"+item.id, queryParams, `${item.vesselName}_${item.voyageNo}_${item.pol}_${item.pod}.xlsx`);
}
const handleCloseAll=()=>{
  if(selectedRows.value.length==0){
    ElMessage.warning("Please select at least one manifest!")
    return
  }
   ElMessageBox.confirm("CONFIRM CLOSED？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(() => {
    const ids=selectedRows.value.map(item=>item.id)
    service.put('/shipping/cargoManifest/batchClose',ids).then(res=>{
      if(res){
        ElNotification.success({
      title: "Prompt information",
      message: "Close manifest success!",
      position: "bottom-right"
    });
        refreshTable()
      }
    })
  })
}
const submitUploadForm = async (data) => { 
  let length= data.photos.length-1
  // @ts-ignore
  const params = {
    id: data.id,
    masterReceipt: data.photos[length]||' '
  };

  await service["put"]("/shipping/cargoManifest/updateMr", params);
  // // @ts-ignore
  ElNotification.success({
    title: "Prompt information",
    message: "save successful!",
    position: "bottom-right"
  });
  refreshTable();
};

const updateFileUpload = (data: any) => {
  refreshTable();
};

const editPrentPod = (flag,index,item) => { 
  isEdit.value = flag
  editIndex.value = index
  if(!flag){
    const params = {
      id: item.id,
      pod: item.pod
    }
    service["put"]("/shipping/cargoManifest/updatePod", params).then(res=>{
      if(res){
        ElMessage.success("Update successful!")
        refreshTable()
      }
    })
  }

}
// 请求搜索下来条件
const getVoyageList = async () => {
  const { data } = await service.get("/shipping/voyage/list", {
    params: { status: 0 }
  });
  if (data) {
    voyages.value = data;
  }
};


// 导入功能
const downTemplateUrl = ref('shipping/cargoManifest/download/template')
const fileType = ref(['.xlsx', '.xls'])
const fileUploadRef = ref(null)
const uploadFileForm = () => {
  proxy.$refs["fileUploadRef"].dialogUploadFileForm()
}
const queryParams = reactive({
  pageNum: 1,
  pageSize: 20,
  vesselName: null,
  voyageNo: null,
  pol: null,
  pod: null, 
  blNo: null,
  type: 0,
  orderByColumn: undefined,
  isAsc: undefined
});

const addClickEvent = ()=>{
  dialogTitle.value = "Add Manifest";
  dialogFormVisible.value = true;
  Object.assign(formParam, initForm);
  isAdd = true;
}

const listData = ref([]);

// 搜索列表
const refreshTable = async () => {
  isLoading.value = true
  listData.value=[]
   service.get("/shipping/cargoManifest/getTable", {
    params: queryParams,
  }).then((res) => {
    if (res) {
      listData.value = res.data;
      total.value = res.total;
      initTableDrag()
    }else{
      listData.value = []
      total.value = 0
    }
  }).finally(() => {
    isLoading.value = false
  })
};
const resetQuery = (data) => {
  Object.assign(queryParams, data)
  listData.value = []
  total.value = 0
}
const custForm = ref();
const dialogTitle = ref("");
const initForm = {
  id: null,
  pol:null,
  pod: null,
  totalWeight: null,
  status: 0,
  type: 0,
  unit: null,
  agencyEn:null,
  agencyCn:null,
  vesselName:null,
  voyageNo:null,
  totalUnits: null,
  totalVolume: null,
  shipper: null,
  consignee: null,
  marks: null,
  blNo: null,
  goodsDesc: null,
  notifyParty:null,
  consigee:null,
  remark: null
}
let isAdd = false;
const units = ["BOXES", "CARTONS", "UNITS", "SKIDS", "PALLETS"]
const selectedRows = ref([])  //多选框

const formParam = reactive(Object.assign({}, initForm));
const dialogFormVisible = ref(false);

const editClickEvent = (row: any,item:any) => {
 
  dialogTitle.value = "Update Manifest";
  dialogFormVisible.value = true;
  Object.keys(initForm).forEach(k => (formParam[k] = row[k]));

  formParam.pod =pods.value.find(val=>val.portName == item.pod)?.fullPortName||''
  isAdd = false;
};

const removeClickEvent = (id) => {
  ElMessageBox.confirm("Confirm to delete the data？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
    await service.delete(`shipping/cargoManifest/${id}`);

    refreshTable();
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "Delete successfully!",
      position: "bottom-right",
    });
  });
};

const handleClose = async (row: any) => {
  ElMessageBox.confirm("CONFIRM CLOSED？", "Confirmation Information", {
    type: "warning",
    confirmButtonText: "Confirm",
    cancelButtonText: "Cancel",
  }).then(async () => {
    await service.put(`shipping/cargoManifest/close`, row)
    ElNotification.success({
      title: "Prompt information",
      message: "Close manifest success!",
      position: "bottom-right"
    });
    refreshTable()
  })
}


 
const search = () => {
  // if(queryParams.voyageNo == null || queryParams.vesselName == null){
  //   ElMessage({
  //     message: "Please select vessel and voyage to query!",
  //     type: "warning"
  //   }); 
  //   return;
  // }
  refreshTable();
};


const selectVessel = async (form:any) => {
  //@ts-ignore
  queryParams.voyageNo = null;
  queryParams.pol = null;
  queryParams.pod = null;
  voyages.value = [];
  pods.value = [];
  pols.value = [];
  let item = vessels.value.find(n => n.vesselName == form.vesselName)
  voyages.value = item.schedules
}

const selectVoyage = async (value) => { 
  //@ts-ignore
  queryParams.pol = null;
  queryParams.pod = null;
  let item = voyages.value.find(n => n.voyageNo == value)
  pods.value = item.pods
  pols.value = item.pols
}

const pageQuery = async (e) => {
  queryParams.pageNum = e.page;
  queryParams.pageSize = e.limit;
  refreshTable();
};

const handleSortChange = async (column: any) => {
  queryParams.orderByColumn = column.prop;
  queryParams.isAsc = column.order; //动态取值排序顺序
  refreshTable();
};

// 多选操作
const handleSelectionChange = (val,item,index) => {
  selectedRows.value =val 
  singles.value[index] = (val.length==1) 
  multiples.value[index] = !val.length; 
}

const submitForm = () => {
  custForm.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    
    await service[isAdd?"post":"put"]("shipping/cargoManifest", formParam);
    // @ts-ignore
    ElNotification.success({
      title: "Prompt information",
      message: "save successful!",
      position: "bottom-right"
    });
    dialogFormVisible.value = false;
    refreshTable()
  });
}  
refreshTable();
</script>
<style lang="scss" scoped>
.manifest-tip-item__wrapper {
  padding-left: 16px;

  &:first-child {
    padding-top: 16px;
  }

  .manifest-tip-item {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    padding: 0 2px 16px 0;
    font-size: 13px;

    .title {
      display: inline-block;
      width: 170px;
    }
    .title1 {
      display: inline-block;
      width: 130px;
    }
    .title2 {
      display: inline-block;
      width: 60px;
    }
  }
}

.block {
  min-height: 100px;

  .el-row {
    margin: 10px 10px 20px;
  }
}
.addupdate-ruleForm {
  .el-form-item {
    margin-bottom: 18px;
  }
}
</style>